import { useEffect, useRef, useState } from "react";
import Hls from 'hls.js';

const CameraView = ({ cameraId }) => {
  const videoRef = useRef(null);
  const hlsRef = useRef(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const initPlayer = () => {
      if (Hls.isSupported()) {
        const hls = new Hls({
          maxBufferLength: 30,
          maxMaxBufferLength: 600,
          maxBufferSize: 60 * 1000 * 1000,
          maxBufferHole: 0.5,
        });
        
        hlsRef.current = hls;
        
        // 使用公共HLS测试流
        const testStreamUrl = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
        hls.loadSource(testStreamUrl);
        hls.attachMedia(videoRef.current);
        
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          setLoading(false);
        });
        
        hls.on(Hls.Events.ERROR, (event, data) => {
          if (data.fatal) {
            setError('视频流加载失败');
            hls.destroy();
          }
        });
      } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
        // Safari原生支持HLS
        const testStreamUrl = 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8';
        videoRef.current.src = testStreamUrl;
        videoRef.current.addEventListener('loadedmetadata', () => {
          setLoading(false);
        });
      } else {
        setError('浏览器不支持视频播放');
      }
    };

    initPlayer();

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy();
      }
    };
  }, [cameraId]);

  return (
    <div className="camera-container">
      {loading && <div className="camera-loading">正在连接摄像头...</div>}
      {error && <div className="camera-error">错误: {error}</div>}
      <div className="video-wrapper">
        <video 
          ref={videoRef} 
          autoPlay 
          playsInline
          muted
          style={{ 
            display: loading || error ? 'none' : 'block'
          }}
          onError={() => setError("视频流加载失败")}
        />
      </div>
    </div>
  );
};

export default CameraView;